<template>
  <div class="login_container">
    <login-box>
      <template #login_form>
        <el-form class="login_form" :model="loginForm" ref="loginForms">
          <div class="login_header">
            <h1>课程管理平台</h1>
            <p>Course Management Platform</p>
          </div>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" v-model="loginForm.username" placeholder="用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" :prefix-icon="Lock" v-model="loginForm.password" show-password placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item prop="usertype" class="usertype">
            <el-radio-group v-model="usertype" style="flex:1;">
              <el-radio value="student" size="large">学生</el-radio>
              <el-radio value="admin" size="large">任课老师</el-radio>
            </el-radio-group>
            <!-- 忘记密码链接 -->
            <el-link type="primary" @click="handleForgetPassword" style="font-size: 16px; font-weight: bold;">忘记密码</el-link>
          </el-form-item>
          <el-form-item>
            <div class="btn-group">
              <el-button v-debounce:500="register" class="register_btn" type="warning" size="large">注册账号</el-button>
              <el-button v-debounce:500="login" :loading="loading" class="login_btn" type="primary" size="large">登录</el-button>
            </div>
          </el-form-item>
        </el-form>
      </template>
    </login-box>
  </div>

</template>
<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue';
import { reactive, ref } from 'vue';
import useUserStore from '@/store/modules/user';
import { ElMessage } from 'element-plus';
//引入管理员相关的小仓库
import useAdminStore from '@/store/modules/admin'; // 命名导入
let adminStore = useAdminStore();
import { parseJwt } from "@/utils/token";

//引入学生相关的小仓库
import useStudentStore from '@/store/modules/student';
let studentStore = useStudentStore();


console.log('useUserStore:', useUserStore());
console.log('useAdminStore:', useAdminStore());
console.log('useStudentStore:', useStudentStore());

import { useRouter } from 'vue-router';
import { ElNotification } from 'element-plus';
import { getTime } from '@/utils/time'
import LoginBox from './layout/index.vue'



// 处理忘记密码点击事件
const handleForgetPassword = () => {
  // 跳转到忘记密码页面或显示相关表单
  $router.push('/forget');
};


//收集账号和密码数据
let usertype = ref('student');
let loginForm = reactive({ username: 'zbthhd', password: '123456' })




//获取路由器
let $router = useRouter();
//定义变量控制按钮加载效果
let loading = ref(false);
//获取el-form组件
let loginForms = ref();
//注册
const register = () => {
  $router.push('/register');
}
//登陆按钮
const login = async () => {
  console.log('开始登录流程');
  console.log('用户类型:', usertype.value);
  console.log('登录表单数据:', loginForm);
  
  //保证表单校验过才能发请求
  try {
    await loginForms.value.validate();
  } catch (error) {
    console.error('表单验证失败:', error);
    ElMessage.error('请填写正确的登录信息');
    return;
  }
  
  //加载，开始加载
  loading.value = true;
  //点击登陆 通知仓库发登陆请求
  //请求成功-》首页
  //登陆失败=》弹出失败信息
  try {
    //保证登陆成功
    console.log('验证通过，准备发送登录请求');
    if (usertype.value === 'student') {
      console.log("学生登录");
      let newLoginForm = reactive({ studentUsername: '', studentPassword: '' })
      newLoginForm.studentUsername = loginForm.username;
      newLoginForm.studentPassword = loginForm.password;
      console.log("提交的学生登录数据:", newLoginForm);
      
      try {
        await studentStore.studentLogin(newLoginForm);
        console.log("学生登录响应成功:", studentStore.token);
        
        if (studentStore.token) {
          let claims = parseJwt(studentStore.token);
          console.log("解析的Token信息:", claims);
          
          if (claims && claims.studentId) {
            console.log("学生ID:", claims.studentId);
            try {
              await studentStore.fetchStudentInfo(claims.studentId);
              console.log("获取学生信息成功");
            } catch (fetchError) {
              console.error("获取学生信息失败:", fetchError);
              ElMessage.warning('登录成功，但获取个人信息失败，部分功能可能受限');
            }
          } else {
            console.error("Token中无学生ID");
          }
          
          // 导航到学生第一个菜单
          console.log("准备跳转到学生页面");
          $router.push('/student/my_project');
          ElMessage.success('登录成功！');
        } else {
          throw new Error("登录成功但未获取到Token");
        }
      } catch (loginError) {
        console.error("学生登录失败:", loginError);
        throw loginError;
      }
      
    } else if (usertype.value === 'admin') {
      console.log("老师登录");
      let newLoginForm = reactive({ adminUsername: '', adminPassword: '' })
      newLoginForm.adminUsername = loginForm.username;
      newLoginForm.adminPassword = loginForm.password;
      console.log("提交的老师登录数据:", newLoginForm);
      
      try {
        await adminStore.adminLogin(newLoginForm);
        console.log("老师登录响应成功:", adminStore.token);
        
        if (adminStore.token) {
          // 导航到管理员第一个菜单
          console.log("准备跳转到管理员页面");
          $router.push('/admin/class_manage');
          ElMessage.success('登录成功！');
        } else {
          throw new Error("登录成功但未获取到Token");
        }
      } catch (loginError) {
        console.error("老师登录失败:", loginError);
        throw loginError;
      }
    }

    ElNotification({
      type: 'success',
      message: `Hi,${getTime()}好`
    });
    //登陆成功，加载消失
    loading.value = false;
  } catch (error: any) {
    //登陆失败，加载消失
    loading.value = false;
    console.error('登录过程中发生错误:', error);
    //登陆失败信息
    ElNotification({
      type: 'error',
      message: error.message || "用户名或密码不正确"
    });
  }
}

// //自定义校验函数
// const validatorUserName = (value: string, callback: Function) => {
//   //rule 校验规则对象 value 表单元素文本内容 callback函数，符合放行，不符合注入错误提示信息
//   if (value.length >= 1) {
//     callback();
//   } else {
//     callback(new Error('账号长度至少为6位'));
//   }
// }
// const validatorPassword = (rule: any, value: string, callback: Function) => {
//   if (value.length >= 6) {
//     callback();
//   } else {
//     callback(new Error('密码长度至少为6位'));
//   }
// }
// //定义表单需要配置的对象
// const rules = {
//   username: [
//     { trigger: 'change', validator: validatorUserName }
//   ],
//   password: [
//     { trigger: 'change', validator: validatorPassword }
//   ]
// }

</script>
<style scoped lang="scss">
.login_container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #004098 0%, #001c44 100%);
}

.login_form {
  position: relative;
  width: 100%;
  padding: 20px;
  border-radius: 8px;
  
  .login_header {
    text-align: center;
    margin-bottom: 30px;
    
    h1 {
      color: #fff;
      font-size: 28px;
      margin-bottom: 5px;
      font-weight: 600;
    }
    
    p {
      color: rgba(255, 255, 255, 0.7);
      font-size: 16px;
    }
  }

  .usertype {
    display: flex;
    justify-content: space-between;
    align-items: center;

    :deep(.el-radio__label) {
      color: #fff;
    }
  }

  :deep(.el-input) {
    .el-input__wrapper {
      background-color: rgba(255, 255, 255, 0.1);
      box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1) inset;
      border-radius: 4px;
    }
    
    input {
      color: #fff;
      height: 45px;
      
      &::placeholder {
        color: rgba(255, 255, 255, 0.5);
      }
    }
    
    .el-input__prefix-inner {
      color: rgba(255, 255, 255, 0.7);
    }
  }
  
  .btn-group {
    display: flex;
    gap: 15px;
    margin-top: 20px;
  }

  .register_btn, .login_btn {
    flex: 1;
    height: 45px;
    border-radius: 4px;
    font-weight: 500;
    letter-spacing: 1px;
  }
  
  .register_btn {
    background: rgba(255, 255, 255, 0.2);
    color: #fff;
    border: none;
    
    &:hover {
      background: rgba(255, 255, 255, 0.3);
    }
  }
  
  .login_btn {
    background: #2e8df5;
    border: none;
    
    &:hover {
      background: #4099ff;
    }
  }
}
</style>